package com.itlong.cloud.commons.service;

import com.itlong.cloud.POJO.PO.AmountChangeInfoPO;
import com.itlong.cloud.POJO.VO.property.PropertyBalanceVO;
import com.itlong.cloud.PlatformConstants;
import com.itlong.cloud.commons.dao.IUpdateAmountDao;
import com.itlong.cloud.commons.queue.UpdateAmountChangeInfoQueue;
import com.itlong.cloud.enumerate.DataStatusEnum;
import com.itlong.cloud.enumerate.TradeTypeEnum;
import com.itlong.cloud.property.service.IPropertyWithdrawService;
import com.itlong.cloud.utils.data.handler.SqlUtil;
import com.itlong.cloud.utils.random.LogicIdUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Service
public class UpdateAmountChangeInfoService {
    private static final Logger LOG = LoggerFactory.getLogger(UpdateAmountChangeInfoService.class);

    @Autowired
    UpdateAmountChangeInfoQueue updateAmountChangeInfoQueue;

    @Autowired
    IUpdateAmountDao iUpdateAmountDao;

    @Autowired
    IPropertyWithdrawService iPropertyWithdrawService;

    private ExecutorService cachedThreadPool ; //线程池

    /**
     * <desc>
     *     新增资金变动明细表(将请求放入队列)
     * </desc>
     *
     * @param amountChangeInfoPO 修改信息
     * @return
     * @author Qiang.S
     * @createDate 2018/09/26
     */
    public boolean updateAmountChangeInfo(AmountChangeInfoPO amountChangeInfoPO){
        try{
            updateAmountChangeInfoQueue.getUpdateAmountChangeInfoQueue().put(amountChangeInfoPO);
        }catch (Exception e){
            LOG.error("新增资金变动明细表加入队列失败！e:" +  e.getMessage());
            return  false;
        }
        return  true;
    }

    /**
     * <desc>
     *     新增资金变动明细表
     * </desc>
     *
     * @return
     * @author Qiang.S
     * @createDate 2018/09/24
     */
    private void doUpdateAmountChangeInfo(){
        try {
            //获取费率信息
            PropertyBalanceVO result = iPropertyWithdrawService.getThirdPartyPaymentInfo();
            DecimalFormat decimalFormat = new DecimalFormat("0.00");
            decimalFormat.setRoundingMode(RoundingMode.HALF_UP);
        while (true) {
                AmountChangeInfoPO amountChangeInfoPO = updateAmountChangeInfoQueue.getUpdateAmountChangeInfoQueue().take();
                if (amountChangeInfoPO != null && !StringUtils.isBlank(amountChangeInfoPO.getProjectId()) && !StringUtils.isBlank(amountChangeInfoPO.getThirdPartyPayment()+"")
                        && !StringUtils.isBlank(amountChangeInfoPO.getTradeAmount()+"")
                        && !StringUtils.isBlank(amountChangeInfoPO.getTradeType()+"") && !StringUtils.isBlank(amountChangeInfoPO.getOutOrderNum())) {
                    //只做 交易类型 1物业抄表费  2维修费 3停车费  9物业增值 的操作
                    if (amountChangeInfoPO.getTradeType() == 1 || amountChangeInfoPO.getTradeType() == 2 || amountChangeInfoPO.getTradeType() == 3 || amountChangeInfoPO.getTradeType() == 9 || amountChangeInfoPO.getTradeType() == 10) {
                        LOG.info("资金明细变动表："+amountChangeInfoPO.getTradeType()+"  "+amountChangeInfoPO.getTradeAmount());
                        // 根据交易类型, 1物业抄表费  2维修费 3停车费 8物业提现查询最后一条 9物业增值 10临时通行
                        AmountChangeInfoPO lastPay = iUpdateAmountDao.getLastAmountChangeInfo(amountChangeInfoPO.getProjectId());
                        // 根据4查询微信商户类型最后一条
                        AmountChangeInfoPO lastWechat = iUpdateAmountDao.getLastAmountWechatInfo();
                        AmountChangeInfoPO payPo = new AmountChangeInfoPO();
                        AmountChangeInfoPO wechatPo = new AmountChangeInfoPO();
                        Date createTime = new Date();
                        BigDecimal handlingFee = new BigDecimal("0");
                        if (amountChangeInfoPO.getTradeType() != 9) {
                            handlingFee = new BigDecimal(amountChangeInfoPO.getTradeAmount().multiply(new BigDecimal(result.getWechatHandlingFee())).multiply(new BigDecimal("0.01")).toString());
                            handlingFee = new BigDecimal(decimalFormat.format(handlingFee));//四舍五入手续费
                        }
                        amountChangeInfoPO.setTradeAmount(amountChangeInfoPO.getTradeAmount().subtract(handlingFee));
                        //支付明细
                        payPo.setChangeId(LogicIdUtil.bussinessId());
                        payPo.setProjectId(amountChangeInfoPO.getProjectId());//项目编号
                        payPo.setHandlingFee(handlingFee);//手续费
                        payPo.setThirdPartyPayment(amountChangeInfoPO.getThirdPartyPayment());//第三方支付 1微信支付 2银联支付
                        payPo.setTradeAmount(amountChangeInfoPO.getTradeAmount());//交易金额
                        payPo.setTradeType(amountChangeInfoPO.getTradeType());//交易类型
                        payPo.setOutOrderNum(amountChangeInfoPO.getOutOrderNum());//外部订单编号
                        payPo.setRemark(amountChangeInfoPO.getRemark());    //交易备注
                        payPo.setStatus(DataStatusEnum.NORMAL.getType());
                        payPo.setCreateTime(createTime);

                        //自动插入微信商户类型明细
                        wechatPo.setChangeId(LogicIdUtil.bussinessId());
                        wechatPo.setProjectId(amountChangeInfoPO.getProjectId());//项目编号
                        wechatPo.setThirdPartyPayment(amountChangeInfoPO.getThirdPartyPayment());//第三方支付 1微信支付 2银联支付
                        wechatPo.setTradeAmount(amountChangeInfoPO.getTradeAmount());//交易金额
                        wechatPo.setTradeType(TradeTypeEnum.WECHAT_MCHI_FEE.getType());//交易类型
                        wechatPo.setOutOrderNum(amountChangeInfoPO.getOutOrderNum());//外部订单编号
                        wechatPo.setStatus(DataStatusEnum.NORMAL.getType());
                        wechatPo.setCreateTime(createTime);
                        if (amountChangeInfoPO.getTradeType() != 9) {
                            if (lastPay == null || lastPay.getTradeAfterAmount() == null) {//支付交易无记录
                                payPo.setTradeBeforeAmount(new BigDecimal("0"));//交易前金额
                                payPo.setTradeAfterAmount(amountChangeInfoPO.getTradeAmount());//交易后金额
                            }else {
                                payPo.setTradeBeforeAmount(lastPay.getTradeAfterAmount());//交易前金额
                                payPo.setTradeAfterAmount(lastPay.getTradeAfterAmount().add(amountChangeInfoPO.getTradeAmount()));//交易后金额
                            }
                            if (lastWechat == null || lastWechat.getTradeAfterAmount() == null) {//微信商户无记录
                                wechatPo.setTradeBeforeAmount(new BigDecimal("0"));//交易前金额
                                wechatPo.setTradeAfterAmount(amountChangeInfoPO.getTradeAmount());//交易后金额
                            }else {
                                wechatPo.setTradeBeforeAmount(lastWechat.getTradeAfterAmount());//交易前金额
                                wechatPo.setTradeAfterAmount(lastWechat.getTradeAfterAmount().add(amountChangeInfoPO.getTradeAmount()));//交易后金额
                            }
                        } else {
                            payPo.setTradeBeforeAmount(lastPay.getTradeAfterAmount());//交易前金额
                            payPo.setTradeAfterAmount(lastPay.getTradeAfterAmount().subtract(amountChangeInfoPO.getTradeAmount()));//交易后金额
                        }
                        Map<String, Object> paramsPay = SqlUtil.durableData(payPo, PlatformConstants.TABLE_SAVE);
                        for(String key : paramsPay.keySet()){
                            if (paramsPay.get(key) != null && "".equals(paramsPay.get(key))) {
                                paramsPay.put(key,null);
                            }
                        }
                        LOG.info("payPo:"+payPo.toString());
                        LOG.info("wechatPo:"+wechatPo.toString());
                        iUpdateAmountDao.save(paramsPay);
                        Map<String, Object> paramsWechat = SqlUtil.durableData(wechatPo, PlatformConstants.TABLE_SAVE);
                        for(String key : paramsWechat.keySet()){
                            if (paramsWechat.get(key) != null && "".equals(paramsWechat.get(key))) {
                                paramsWechat.put(key,null);
                            }
                        }
                        // 当类型为物业增值时，为平台扣除增值费，与微信无关，则不保存微信商户类型明细
                        if (amountChangeInfoPO.getTradeType() != 9) {
                            iUpdateAmountDao.save(paramsWechat);
                        }
                        Thread.sleep(500);//防止数据库数据不同步,每执行一次等待0.5秒
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            LOG.error("【新增资金变动明细表异常】");
        }
    }
    /**
     * <desc>
     *      初始化
     * </desc>
     *
     * @author Qiang.S
     * @createDate 2018/09/26
     */
    @PostConstruct
    public void init(){
        cachedThreadPool = Executors.newSingleThreadExecutor();
            cachedThreadPool.execute(() -> {
                doUpdateAmountChangeInfo();
            });
    }
}
